//
//  TT_OSSManager.m
//  ZKGX
//
//  Created by 王洋 on 2020/3/12.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "AFNetworking.h"
#import "TT_OSSManager.h"
#import "UIImage+FixOrientation.h"
#import <AliyunOSSiOS/OSSService.h>

@implementation TT_OSSManager

+(void)uploadPhoto:(NSMutableArray <NSData *>*)imageArray type:(NSString *)imageType FinishBlock:(finishBlock)finishBlock UploadProgress:(UploadProgress)uploadProgress FailedBlock:(FailedBlock)failedBlock{
//    if (imageArray.count == 0){
//        finishBlock(nil);
//        return;
//    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSMutableArray *imagePathArray = @[].mutableCopy;
        
        for (NSData *imageD in imageArray){
            if ([imageD isKindOfClass:NSString.class]){
                [imagePathArray addObject:imageD];
                if (imagePathArray.count == imageArray.count){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        finishBlock(imagePathArray);
                    });
                }else{
                    if (uploadProgress){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            uploadProgress(imagePathArray.count*100/imageArray.count);
                        });
                    }
                }
                continue;
            }
            OSSPutObjectRequest * put = [OSSPutObjectRequest new];
            put.bucketName = OSSBUCKET_NAME;
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy/MM/dd";
            NSString *timeStr = [formatter stringFromDate:[NSDate date]];
            put.objectKey = [NSString stringWithFormat:@"%@/%@/iOS/%@.jpg",imageType,timeStr,[self uuidString]];
            
            
            UIImage *im = [UIImage imageWithData:imageD];
            im = [im fixOrientation];
            NSData *imageDataPng = UIImageJPEGRepresentation(im,1);
            put.uploadingData = imageDataPng; // 直接上传NSData
            [imagePathArray addObject:put.objectKey];
            OSSTask * putTask = [[self aliOSSClient] putObject:put];
            
            
            [putTask continueWithBlock:^id(OSSTask *task) {
                if (!task.error) {
                    NSLog(@"upload object success!");
                } else {
                    NSLog(@"upload object failed, error: %@" , task.error);
                }
                return nil;
            }];
            
            [putTask waitUntilFinished];

            if (!putTask.error) {
                if (imagePathArray.count == imageArray.count){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        finishBlock(imagePathArray);
                    });
                }else{
                    if (uploadProgress){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            uploadProgress(imagePathArray.count*100/imageArray.count);
                        });
                    }
                }
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    finishBlock(nil);
                });
                
            }
        }
    });
}

+ (OSSClient *)aliOSSClient {
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OSS_AccessKeyId secretKey:OSS_AccessKeySecret];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =60;
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;
    
    [OSSLog enableLog];
    // 你的阿里地址前面通常是这种格式 ：http://oss……
    OSSClient *aliOSSClient = [[OSSClient alloc] initWithEndpoint:OSS_ENDPOINT credentialProvider:credential];
    return aliOSSClient;
}

+ (NSString *)uuidString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

+ (void)uploadImagesWithPath:(NSString *)path
                      params:(NSDictionary *)params
                      images:(UIImage *)images
                     success:(finishBlock)success
                     failure:(FailedBlock)failure
                    progress:(UploadProgress)progress {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // ContentType设置
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    
    // 上传完整地址
    NSString * urlString = TT_Global_Source_Domain;
    
    [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (images != nil) {
        NSData *data = UIImageJPEGRepresentation(images, 0.2f);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 上传进度
        progress(uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        NSLog(@"上传成功%@",responseObject);
        NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
        success(jsonDict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败%@",error);
        failure(error);
    }];
}


+ (void)uploadVoicesWithPath:(NSString *)path
                      params:(NSDictionary *)params
                    filePath:(NSString *)filePath
                     success:(finishBlock)success
                     failure:(FailedBlock)failure
                    progress:(UploadProgress)progress {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    
    NSString * urlString = TT_Global_Source_Domain;
    
    [manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (filePath.length > 0) {

        NSData *data= [NSData dataWithContentsOfFile:filePath];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";

        NSString *fileName = [NSString stringWithFormat:@"%@.MP3", [self uuidString]];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"mp3/wmr"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 上传进度
        progress(uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
     
        NSLog(@"上传成功%@",responseObject);
        NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
        success(jsonDict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败%@",error);
        failure(error);
    }];
}


+ (void)downloadAudioWithUrl:(NSString *)url
           saveDirectoryPath:(NSString *)directoryPath
                    fileName:(NSString *)fileName
                      finish:(finishBlock )finishBlock
                      failed:(FailedBlock)failed {
    NSString *file_path = [directoryPath stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    /// 判断文件是否已经存在
    if ([fm fileExistsAtPath:file_path])
    {
        finishBlock(file_path);
    }
    /// 不存在时
    else
    {
        NSURL *URL = [NSURL URLWithString:url];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        //AFN3.0+基于封住URLSession的句柄
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        //请求
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        //下载Task操作
        NSURLSessionDownloadTask *_downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            //进度
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
            return [NSURL fileURLWithPath:path];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            // filePath就是你下载文件的位置，你可以解压，也可以直接拿来使用
            NSString *armFilePath = [filePath path];// 将NSURL转成NSString

            finishBlock(armFilePath);
        }];
        [_downloadTask resume];
    }
}

@end
